package com.xr.miniprogram.controller.pay;


import com.google.gson.Gson;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.xr.common.config.WechatPay2ValidatorForRequest;
import com.xr.common.core.controller.BaseController;
import com.xr.common.core.domain.AjaxResult;
import com.xr.common.utils.HttpUtils;
import com.xr.miniprogram.domain.vo.WxPayRespVO;
import com.xr.miniprogram.service.WXPayService;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/miniprogram/pay")
public class MiniProgramPayController extends BaseController {
    @Resource
    private WXPayService wxPayService;
    @Resource
    private Verifier verifier;

    @ApiOperation("预支付")
    @RequestMapping("/createOrder/{orderId}")
    public AjaxResult create(@PathVariable("orderId") Long orderId) throws Exception {
        WxPayRespVO wxPayRespVO = wxPayService.createOrder(orderId);
        return success(wxPayRespVO);
    }


    @Operation(summary = "支付回调通知")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request, HttpServletResponse response){
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        //处理通知参数
        try {
            String data = HttpUtils.readData(request);
            Map<String,Object> bodyMap = gson.fromJson(data, HashMap.class);
            String requestId = (String) bodyMap.get("id");
            log.info("支付通知的id-->{}",requestId);
            log.info("回调的内容：{}",data);

            //签名验证
            WechatPay2ValidatorForRequest wechatPay2ValidatorForRequest = new WechatPay2ValidatorForRequest(verifier, requestId,data);
            if(!wechatPay2ValidatorForRequest.validate(request)){
                log.info("验签失败");
                response.setStatus(500);
                map.put("code","ERROR");
                map.put("message","验签失败");
                return gson.toJson(map);
            }
            log.info("验签成功");
            //处理订单
            wxPayService.processOrder(bodyMap);
            //成功应答
            response.setStatus(200);
            map.put("code","SUCCESS");
            map.put("message","成功");
            return gson.toJson(map);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            map.put("code","ERROR");
            map.put("message","失败");
            return gson.toJson(map);
        }
    }

    /**
     * 关闭订单
     * @param orderNo
     * @return
     * @throws Exception
     */
    @RequestMapping("/close/{orderNo}")
    public AjaxResult close(@PathVariable("orderNo") String orderNo) throws Exception {
        wxPayService.closePayOrder(orderNo);
        return success();
    }

    /**
     * 主动调用-订单状态查询
     * @param orderNo
     * @return
     * @throws Exception
     */
    @ApiOperation("微信支付-订单状态查询")
    @RequestMapping("/queryOrder/{orderNo}")
    public AjaxResult queryOrder(@PathVariable("orderNo") String orderNo) throws Exception {
        return success(wxPayService.queryOrder(orderNo));
    }

    @Operation(summary = "交易订单退款申请" , description = "交易订单退款申请" )
    @RequestMapping("/refundOrder/{orderNo}" )
    public AjaxResult reviewRefundById(@PathVariable("orderNo") String orderNo) throws Exception {
        wxPayService.refundOrder(orderNo);
        return success();
    }

    @ApiOperation("查询退款")
    @RequestMapping("/refund/{refundNo}" )
    public AjaxResult queryRefund(@PathVariable("refundNo") String refundNo) throws Exception {
        return success(wxPayService.queryRefund(refundNo));
    }
    @Operation(summary = "退款结果通知")
    @PostMapping("/refunds/notify")
    public String refundNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("退款通知执行");
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        //处理通知参数
        try {
            String data = HttpUtils.readData(request);
            Map<String,Object> bodyMap = gson.fromJson(data, HashMap.class);
            String requestId = (String) bodyMap.get("id");
            log.info("支付通知的id-->{}",requestId);

            //签名验证
            WechatPay2ValidatorForRequest wechatPay2ValidatorForRequest = new WechatPay2ValidatorForRequest(verifier, requestId,data);
            if(!wechatPay2ValidatorForRequest.validate(request)){
                log.info("验签失败");
                response.setStatus(500);
                map.put("code","ERROR");
                map.put("message","验签失败");
                return gson.toJson(map);
            }
            log.info("验签成功");
            //处理退款订单
            wxPayService.processRefundOrder(bodyMap);
            //成功应答
            response.setStatus(200);
            map.put("code","SUCCESS");
            map.put("message","成功");
            return gson.toJson(map);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            map.put("code","ERROR");
            map.put("message","失败");
            return gson.toJson(map);
        }
    }
}
